Yashb | How to Make the Snake Game Using JavaScript?
Home / JavaScript

How to Make the Snake Game Using JavaScript?

Warawreh 24 Feb, 2023 15 min

Table of contents

How to Make the Snake Game Using JavaScript?

The Snake game is a classic arcade game that has been around for decades. It was first created in the mid-1970s by a programmer named Gremlin Industries, and since then, it has become one of the most popular games of all time. The game has been ported to almost every platform imaginable, from early home computers like the Commodore 64 and the Apple II to modern smartphones and web browsers. It's a simple but addictive game that has stood the test of time, and it continues to be enjoyed by millions of people around the world.

 

The basic premise of the Snake game is simple. You control a snake that moves around the screen, eating food and growing longer with each piece it consumes. As the snake grows longer, it becomes more difficult to maneuver without running into the walls or its own tail. The game ends when the snake crashes into a wall or its own tail, and the player's score is based on how long the snake was able to survive.

 

The gameplay is straightforward, but there are many variations of the game that add additional elements to keep things interesting. Some versions of the game have power-ups that give the snake special abilities or make it invincible for a short period of time. Others introduce obstacles or hazards that the snake must avoid, such as bombs or spikes. Still, others have multiple snakes that the player must control simultaneously, adding an extra layer of challenge.

 

The Snake game has inspired countless clones and variations over the years, and it has been used as the basis for many other games. For example, the popular mobile game "Agar.io" is essentially a multiplayer version of the Snake game, where players control cells that consume other cells and grow larger. The Snake game has also been used as a teaching tool for computer programming, with many programmers creating their own versions of the game as a way to learn new programming techniques.

 

Steps to make


To make the Snake game using JavaScript, you can follow these steps:

 

1-     Create a canvas element in your HTML file where the game will be displayed.

<canvas id="canvas" a="400" height="400"></canvas>

 

2-     Initialize the canvas context in JavaScript and set up the game variables.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var snake = [{ x: 10, y: 10 }];
var direction = "right";
var food = { x: 0, y: 0 };
var score = 0;

var gameLoop;
var gameOver = false;

 

 

3-     Create a function to draw the game board, including the snake and food.

function draw() {
  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the snake
  ctx.fillStyle = "green";
  for (var i = 0; i < snake.length; i++) {
    ctx.fillRect(snake[i].x, snake[i].y, 1, 1);
  }

  // Draw the food
  ctx.fillStyle = "red";
  ctx.fillRect(food.x, food.y, 1, 1);

  // Display the score
  ctx.fillStyle = "black";
  ctx.fillText("Score: " + score, 10, canvas.height - 10);
}

4-     Create a function to update the game state on each frame of the game loop.

function update() {
  // Move the snake
  var head = { x: snake[0].x, y: snake[0].y };
  if (direction === "right") head.x++;
  if (direction === "left") head.x--;
  if (direction === "up") head.y--;
  if (direction === "down") head.y++;
  snake.unshift(head);

  // Check if the snake has collided with the walls or itself
  if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
    gameOver = true;
  }
  for (var i = 1; i < snake.length; i++) {
    if (head.x === snake[i].x && head.y === snake[i].y) {
      gameOver = true;
    }
  }

  // Check if the snake has eaten the food
  if (head.x === food.x && head.y === food.y) {
    score++;
    generateFood();
  } else {
    snake.pop();
  }
}

5-     Create a function to generate the food randomly on the canvas.

function generateFood() {
  food.x = Math.floor(Math.random() * canvas.width);
  food.y = Math.floor(Math.random() * canvas.height);
}

6-     Add event listeners to detect when the player presses the arrow keys to change the direction of the snake.

document.addEventListener("keydown", function (event) {
  if (event.keyCode === 37 && direction !== "right") direction = "left";
  if (event.keyCode === 38 && direction !== "down") direction = "up";
  if (event.keyCode === 39 && direction !== "left") direction = "right";
  if (event.keyCode === 40 && direction !== "up") direction = "down";
});

7-     Start the game loop and update the game state and draw the game board on each frame.

function game() {
  update();
  draw();

  if (gameOver) {
    clearInterval(gameLoop);
    alert("Game Over!");
  }
}
generateFood();
gameLoop = setInterval(game, 100);

8-     Create a game function that calls the update and draw functions and checks for the game over condition.

function game() {
  update();
  draw();

  if (gameOver) {
    clearInterval(gameLoop);
    alert("Game Over!");
  }
}

9-     Create a function to handle the game over condition.

function gameOver() {
  clearInterval(gameLoop);
  alert("Game Over!");
}

10-  Create a function to reset the game variables when the game is restarted.

function resetGame() {
  snake = [{ x: 10, y: 10 }];
  direction = "right";
  food = { x: 0, y: 0 };
  score = 0;
  gameOver = false;
}

11-  Modify the update function to check for the game over condition and reset the game when it is over.

function update() {
  // Move the snake
  var head = { x: snake[0].x, y: snake[0].y };
  if (direction === "right") head.x++;
  if (direction === "left") head.x--;
  if (direction === "up") head.y--;
  if (direction === "down") head.y++;
  snake.unshift(head);

  // Check if the snake has collided with the walls or itself
  if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
    gameOver();
  }
  for (var i = 1; i < snake.length; i++) {
    if (head.x === snake[i].x && head.y === snake[i].y) {
      gameOver();
    }
  }

  // Check if the snake has eaten the food
  if (head.x === food.x && head.y === food.y) {
    score++;
    generateFood();
  } else {
    snake.pop();
  }
}

12-  Add a restart button to the HTML file and create a function to handle the click event.

<button id="restart-button">Restart</button>



document.getElementById("restart-button").addEventListener("click", function () {
  resetGame();
  generateFood();
  gameLoop = setInterval(game, 100);
});

 

And that's it! These steps will help you create a simple Snake game using JavaScript.

 

Complete Code


here's the complete code for creating a simple Snake game using JavaScript:

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Snake Game</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="game-board" a="300" height="300"></canvas>
    <p>Score: <span id="score"></span></p>
    <button id="restart-button">Restart</button>
    <script src="snake.js"></script>
  </body>
</html>

 

 

JavaScript (snake.js):

var canvas = document.getElementById("game-board");
var ctx = canvas.getContext("2d");

// Variables
var snake = [{ x: 10, y: 10 }];
var direction = "right";
var food = { x: 0, y: 0 };
var score = 0;
var gameOver = false;


// Functions
function draw() {
  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the snake
  ctx.fillStyle = "green";
  for (var i = 0; i < snake.length; i++) {
    ctx.fillRect(snake[i].x * 10, snake[i].y * 10, 10, 10);
  }

  // Draw the food
  ctx.fillStyle = "red";
  ctx.fillRect(food.x * 10, food.y * 10, 10, 10);

  // Update the score
  document.getElementById("score").textContent = score;
}

function update() {
  // Move the snake
  var head = { x: snake[0].x, y: snake[0].y };
  if (direction === "right") head.x++;
  if (direction === "left") head.x--;
  if (direction === "up") head.y--;
  if (direction === "down") head.y++;
  snake.unshift(head);

  // Check if the snake has collided with the walls or itself
  if (head.x < 0 || head.x >= canvas.width/10 || head.y < 0 || head.y >= canvas.height/10) {
    clearInterval(gameLoop);
    alert("Game Over!");
  }
  for (var i = 1; i < snake.length; i++) {
    if (head.x === snake[i].x && head.y === snake[i].y) {
      clearInterval(gameLoop);
      alert("Game Over!");
    }
  }

  // Check if the snake has eaten the food
  if (head.x === food.x && head.y === food.y) {
    score++;
    generateFood();
  } else {
    snake.pop();
  }
}

function generateFood() {
  var x = Math.floor(Math.random() * canvas.width / 10);
  var y = Math.floor(Math.random() * canvas.height / 10);
  food = { x: x, y: y };
}


function resetGame() {
  snake = [{ x: 10, y: 10 }];
  direction = "right";
  food = { x: 0, y: 0 };
  score = 0;
  gameOver = false;
}

function game() {
  update();
  draw();

  if (gameOver) {
    clearInterval(gameLoop);
    alert("Game Over!");
  }
}

document.addEventListener("keydown", function (event) {
  if (event.keyCode === 37 && direction !== "right") direction = "left";
  if (event.keyCode === 38 && direction !== "down") direction = "up";
  if (event.keyCode === 39 && direction !== "left") direction = "right";
  if (event.keyCode === 40 && direction !== "up") direction = "down";
});

generateFood();
gameLoop = setInterval(game, 100);



function resetGame() {
  snake = [{ x: 10, y: 10 }];
  direction = "right";
  food = { x: 0, y: 0 };
  score = 0;
  gameOver = false;
}

document.getElementById("restart-button").addEventListener("click", function () {
  resetGame();
  generateFood();
  gameLoop = setInterval(game, 100);
});

 

 

Conclusion


Despite its simplicity, the Snake game remains a beloved classic that continues to be enjoyed by players of all ages. Whether you're a seasoned gamer or just looking for a fun way to pass the time, the Snake game is a timeless classic that never gets old. So fire up your favorite version of the game, grab some snacks, and settle in for a few hours of addictive, high-score-chasing fun!





Read Also

How to Make the Snake Game Using JavaScript?
Kaggle Competitions
Federated Learning
YOLO Real-Time Object Detection
Time series forecasting

Most Read

What is big O notation (The complexity) and how to calculate it?
Stack
Queue
Deque
Prime numbers